const Verify = require('../verify_mpsdk/main');
var client = {};

// 演练环境
var ip1 = "https://xf.turingsingularity.com/api/";
// 开发环境203服务器
var ip = "https://fq.turingsingularity.com/api/";
var token = "ca261a6a477e4b3ebffae56baff14cf8";
var bizToken = "1E882371-DF61-4DDE-938C-83E8EAC9888A";
var taskId = "3bcfb499-c27d-11ea-b15e-0242ac110004";

// 获取验证码接口
client.getCode = function (
  callback,
  nameInputValue,
  certifyCardType1,
  idcardInputValue,
  phoneInputValue
) {
  wx.request({
    url: ip + "ca796e24-2601-4eca-8878-cc2c6af2bba4",
    method: "POST",
    data: {
      phone: phoneInputValue,
      name: nameInputValue,
      certificateCode: idcardInputValue,
      certificateType: certifyCardType1
    },
    // 期望返回的数据格式，默认json，支持json，text，base64
    dataType: "json",
    // 调用成功的回调函数
    success: function (res) {
      if (res.data.succeed == 0) {
        token = res.data.setToken;
        wx.showToast({
          title: '获取验证码成功',
          icon: 'none',
          duration: 1000
        })
        console.log("res.data.setToken   ", res.data.setToken);
        wx.setStorageSync('token', res.data.setToken);
      } else {
        wx.showToast({
          title: "获取验证码失败",
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 登录接口
client.login = function (
  callback,
  phoneInputValue,
  codeInputValue,
  certifyCardType
) {
  token = wx.getStorageSync('token');
  console.log("token: " + token);
  wx.request({
    url: ip + "d22f1d56-607c-4651-a0bf-b4b326468464",
    method: "POST",
    data: {
      code: codeInputValue
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.showToast({
          title: '登录成功',
          icon: 'none',
          duration: 1000
        });

        if (certifyCardType == "0") {
          bizToken = res.data.data;
          // 调用实名核身功能
          wx.startVerify({
            data: {
              token: bizToken // BizToken
            },
            success: (res) => { // 验证成功后触发
              console.log("startVerify: " + JSON.stringify(res));
              // res 包含验证成功的token, 这里需要加500ms延时，防止iOS下不执行后面的逻辑
              setTimeout(() => {
                // 验证成功后，拿到token后的逻辑处理，具体以客户自身逻辑为准
                // getFaceResult
                client.sendBizToken(bizToken);
              }, 500);
            },
            fail: (err) => { // 验证失败时触发
              // err 包含错误码，错误信息，弹窗提示错误
              setTimeout(() => {
                wx.showModal({
                  title: "提示",
                  content: err.ErrorMsg,
                  showCancel: false
                })
              }, 500);
            }
          });
        } else {
          // 已登录成功
          wx.setStorageSync('logined', true);
          wx.redirectTo({
            url: "../../pages/main/main"
          });
        }
      } else {
        wx.showToast({
          title: '登录失败: ' + res.data.errorMsg,
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 人脸核身sendBizToken接口
client.sendBizToken = function (bizToken) {
  console.log("sendBizToken");
  wx.request({
    url: ip + "8b667f2a-dfbc-4b92-b647-79420cb14723",
    method: "POST",
    data: {
      bizToken: bizToken
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.showToast({
          title: '人脸识别成功',
          icon: 'none',
          duration: 1000
        });
        // 已登录成功
        wx.setStorageSync('logined', true);
        wx.redirectTo({
          url: "../../pages/main/main"
        });
      } else {
        wx.showToast({
          title: '人脸识别失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// 获取公证申请列表接口
client.listTasksByLiableUserId = function (callback, that) {
  wx.request({
    url: ip + "0ffeebf5-8f8d-4dc3-a442-6c74cef29f1e",
    method: "POST",
    data: {
      "page": "0",
      "size": "999999"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        for (var i = 0; i < res.data.data.content.length; i++) {
          res.data.data.content[i].checkHidden = true;
          switch (res.data.data.content[i].taskStatus) {
            //0000-银行申办中----------------------银行申办中（债 务人担保人任务列表中不展示该任务） 
            case "0000":
              res.data.data.content[i].taskStatus = "银行申办中";
              res.data.data.content[i].statusColor = "#09BB07";
              break;
              //0001-银行申办完成--------------------申请 
            case "0001":
              res.data.data.content[i].taskStatus = "银行申办完成";
              res.data.data.content[i].statusColor = "#09BB07";
              break;
              //0002-待询问----------------书面询问/视频询问  支付 
            case "0002":
              res.data.data.content[i].taskStatus = "待询问";
              res.data.data.content[i].statusColor = "#09BB07";
              break;
              //0003-收费确认中-------查看申请 
            case "0003":
              res.data.data.content[i].taskStatus = "收费确认中";
              res.data.data.content[i].statusColor = "#00BFBF";
              break;
              //0004-待公证审核-------------------查看申请 
            case "0004":
              res.data.data.content[i].taskStatus = "待公证审核";
              res.data.data.content[i].statusColor = "#00BFBF";
              break;
              //0005-已通过-----------------查看申请 
            case "0005":
              res.data.data.content[i].taskStatus = "已通过";
              res.data.data.content[i].statusColor = "#00BFBF";
              break;
              //0006-已出证-------查看申请 查看证书 
            case "0006":
              res.data.data.content[i].taskStatus = "已出证";
              res.data.data.content[i].statusColor = "#D7D7D7";
              res.data.data.content[i].checkHidden = false;
              break;
              //0007-不通过--------------申请   
            case "0007":
              res.data.data.content[i].taskStatus = "不通过";
              res.data.data.content[i].statusColor = "#D9001B";
              break;
              //0008-停止办理
            case "0008":
              res.data.data.content[i].taskStatus = "停止办理";
              res.data.data.content[i].statusColor = "#D9001B";
              break;
          }
          // 0: 银行付费；1：债务人付费
          if (res.data.data.content[i].payChargeType == "0") {
            res.data.data.content[i].payChargeType = "银行付费"
          } else {
            res.data.data.content[i].payChargeType = "债务人付费"
          }
          switch (res.data.data.content[i].operationStatus) {
            //0000-未做签名-----------------------申请
            case "0000":
              res.data.data.content[i].operationStatus = "申 请";
              res.data.data.content[i].operationStatusColor = "#1C6FFF";
              res.data.data.content[i].paperAskColor = "#DBDBDB";
              break;
              //0001-公证文档签名完成---------------查看申请 书面询问/视频询问
            case "0001":
              res.data.data.content[i].operationStatus = "查看申请";
              res.data.data.content[i].operationStatusColor = "#333333";
              res.data.data.content[i].paperAskColor = "#1C6FFF";
              break;
              //0002-书面或视频询问完成---------------- 查看申请 支付(若isPayUser==1)
            case "0002":
              res.data.data.content[i].operationStatus = "查看申请";
              res.data.data.content[i].operationStatusColor = "#333333";
              res.data.data.content[i].paperAskColor = "#DBDBDB";
              break;
          }
          // 0: 书面询问；1：在线视频询问
          if (res.data.data.content[i].enquireMethod == "0") {
            res.data.data.content[i].enquireMethod = "书面询问"
          } else {
            res.data.data.content[i].enquireMethod = "在线询问"
          }
        }
        that.setData({
          applyList: res.data.data.content
        });
      } else {
        wx.showToast({
          title: '获取公证申请列表失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 判断当前用户是否已授权接口
client.getUserByUserInfoUserId = function (callback, taskId1, that) {
  taskId = taskId1;
  wx.request({
    url: ip + "26abcf84-a0b9-4ec5-8955-b43c2978f22f",
    method: "POST",
    data: {
      "page": "0"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(token);
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        if ("0" == res.data.data.user.partyAuthorizedStatus) {
          that.setData({
            agreementOpened: false
          });
        } else {
          wx.navigateTo({
            url: "../../pages/apply/apply?taskId=" + taskId
          });
        }
      } else {
        wx.showToast({
          title: '判断授权失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// 授权对话框获取验证码接口
client.electronicSignatureAuthorize = function (callback, that) {
  wx.request({
    url: ip + "9ff756be-c92f-49ce-8356-9817f0b71308",
    method: "POST",
    data: {
      userType: "5"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        if (res.data.data == "已经开通代签权限") {
          wx.showToast({
            title: '已经开通代签权限',
            icon: 'none',
            duration: 1000
          });
          that.setData({
            agreementOpened: true
          });
          wx.navigateTo({
            url: "../../pages/apply/apply?taskId=" + taskId
          });
        } else {
          wx.showToast({
            title: '获取验证码成功',
            icon: 'none',
            duration: 1000
          });
        }
      } else {
        wx.showToast({
          title: '获取验证码失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// 授权对话框验证码校验接口
client.authorizeCheck = function (callback, verifyCode, that) {
  wx.request({
    url: ip + "0b35ea6d-1373-4d8c-bec2-9c40a2789277",
    method: "POST",
    data: {
      userType: "5",
      verifyCode: verifyCode
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.showToast({
          title: '授权成功',
          icon: 'none',
          duration: 1000
        });
        that.setData({
          agreementOpened: true
        });
        wx.navigateTo({
          url: "../../pages/apply/apply?taskId=" + taskId
        });
      } else {
        wx.showToast({
          title: '授权失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// （第一页）获取合同和当前登录人信息接口
client.getContractsAndCurrentUserByTaskId = function (callback, taskId1, that) {
  taskId = taskId1;
  wx.request({
    url: ip + "e33f736a-583b-47cb-ae25-f420506d66db",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      // console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        res.data.data.contracts[0].contractSignDate = client.transTime(res.data.data.contracts[0].contractSignDate);
        // 0-女/1-男
        if (res.data.data.user.gender == "0") {
          res.data.data.user.gender = "女"
        } else {
          res.data.data.user.gender = "男"
        }
        // 0-居民身份证/1-港澳居民往来内地通行证/2-台湾居民往来内地通行证/3-护照
        switch (res.data.data.user.certificateType) {
          case "0":
            res.data.data.user.certificateType = "居民身份证";
            break;
          case "1":
            res.data.data.user.certificateType = "港澳居民往来内地通行证";
            break;
          case "2":
            res.data.data.user.certificateType = "台湾居民往来内地通行证";
            break;
          case "3":
            res.data.data.user.certificateType = "护照";
            break;
        }
        // 0-未婚/1-已婚/2-离婚
        if (res.data.data.user.maritalStatus == "0") {
          res.data.data.user.maritalStatus = "未婚"
        } else if (res.data.data.user.maritalStatus == "1") {
          res.data.data.user.maritalStatus = "已婚"
        } else {
          res.data.data.user.maritalStatus = "离婚"
        }
        that.setData({
          contracts: res.data.data.contracts,
          user: res.data.data.user
        });
      } else {
        wx.showToast({
          title: '获取合同信息失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// 修改手机号邮箱接口
client.modifyContractLiableUserBreakContract = function (
  callback,
  breakContractEmail,
  breakContractPhone,
  that
) {
  wx.request({
    url: ip + "0d86466a-8cac-4d09-b2f7-1188d5165068",
    method: "POST",
    data: {
      taskId: taskId,
      breakContractEmail: breakContractEmail,
      breakContractPhone: breakContractPhone
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.showToast({
          title: '修改手机号邮箱成功',
          icon: 'none',
          duration: 1000
        });
        wx.redirectTo({
          url: "../../pages/apply2/apply2?taskId=" + taskId
        });
      } else {
        wx.showToast({
          title: '修改手机号邮箱失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 4页1 查询《公证申请表》参数 getNotarialApplicationFormArgumentsByTaskIdAndUserInfoId
client.getNotarialApplicationFormArgumentsByTaskIdAndUserInfoId = function (taskId, that) {
  wx.request({
    url: ip + "61ab65f1-2a16-45c2-891f-1d1606a29be7",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        var isPerson = true;
        if (res.data.data.notarialApplicationFormArguments.currentUserType != "5") {
          isPerson = false;
        }
        // 0-女/1-男
        if (res.data.data.notarialApplicationFormArguments.applicants[0].personalGender == "0") {
          res.data.data.notarialApplicationFormArguments.applicants[0].personalGender = "女"
        } else {
          res.data.data.notarialApplicationFormArguments.applicants[0].personalGender = "男"
        }
        // 0-居民身份证/1-港澳居民往来内地通行证/2-台湾居民往来内地通行证/3-护照
        switch (res.data.data.notarialApplicationFormArguments.applicants[0].personalCertificateType) {
          case "0":
            res.data.data.notarialApplicationFormArguments.applicants[0].personalCertificateType = "居民身份证";
            break;
          case "1":
            res.data.data.notarialApplicationFormArguments.applicants[0].personalCertificateType = "港澳居民往来内地通行证";
            break;
          case "2":
            res.data.data.notarialApplicationFormArguments.applicants[0].personalCertificateType = "台湾居民往来内地通行证";
            break;
          case "3":
            res.data.data.notarialApplicationFormArguments.applicants[0].personalCertificateType = "护照";
            break;
        }
        // 0-女/1-男
        if (res.data.data.notarialApplicationFormArguments.applicants[0].orgLegalRepresentativeGender == "0") {
          res.data.data.notarialApplicationFormArguments.applicants[0].orgLegalRepresentativeGender = "女"
        } else {
          res.data.data.notarialApplicationFormArguments.applicants[0].orgLegalRepresentativeGender = "男"
        }
        // 0-女/1-男
        if (res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentGender == "0") {
          res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentGender = "女"
        } else {
          res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentGender = "男"
        }
        // 0-居民身份证/1-港澳居民往来内地通行证/2-台湾居民往来内地通行证/3-护照
        switch (res.data.data.notarialApplicationFormArguments.applicants[0].legalRepresentativeCertificateType) {
          case "0":
            res.data.data.notarialApplicationFormArguments.applicants[0].legalRepresentativeCertificateType = "居民身份证";
            break;
          case "1":
            res.data.data.notarialApplicationFormArguments.applicants[0].legalRepresentativeCertificateType = "港澳居民往来内地通行证";
            break;
          case "2":
            res.data.data.notarialApplicationFormArguments.applicants[0].legalRepresentativeCertificateType = "台湾居民往来内地通行证";
            break;
          case "3":
            res.data.data.notarialApplicationFormArguments.applicants[0].legalRepresentativeCertificateType = "护照";
            break;
        }
        // 0-居民身份证/1-港澳居民往来内地通行证/2-台湾居民往来内地通行证/3-护照
        switch (res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentCertificateType) {
          case "0":
            res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentCertificateType = "居民身份证";
            break;
          case "1":
            res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentCertificateType = "港澳居民往来内地通行证";
            break;
          case "2":
            res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentCertificateType = "台湾居民往来内地通行证";
            break;
          case "3":
            res.data.data.notarialApplicationFormArguments.applicants[0].orgAuthorizedAgentCertificateType = "护照";
            break;
        }
        that.setData({
          notarialApplicationFormArguments: res.data.data.notarialApplicationFormArguments,
          isPerson: isPerson
        });
      } else {
        wx.showToast({
          title: '获取公证文档参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
    }
  });
};

// 4页2 查询《受理通知与告知书》参数 getAcceptanceNoticeAndNotificationArgumentsByTaskIdAndUserInfoId
client.getAcceptanceNoticeAndNotificationArgumentsByTaskIdAndUserInfoId = function (taskId, that) {
  wx.request({
    url: ip + "4b54f301-5933-4e36-8804-251ee9f91188",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        var applicantNames = "";
        for (var i = 0; i < res.data.data.acceptanceNoticeAndNotificationArguments.applicantNames.length; i++) {
          applicantNames += res.data.data.acceptanceNoticeAndNotificationArguments.applicantNames[i] + "、"
        }
        that.setData({
          acceptanceNoticeAndNotificationArguments: res.data.data.acceptanceNoticeAndNotificationArguments,
          applicantNames: applicantNames
        });
      } else {
        wx.showToast({
          title: '获取公证文档参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
    }
  });
};

// 4页3 查询《承诺书》参数 getLetterOfCommitmentArgumentsByTaskIdAndUserInfoId
client.getLetterOfCommitmentArgumentsByTaskIdAndUserInfoId = function (taskId, that) {
  wx.request({
    url: ip + "dde28e09-daab-4483-b93c-e4058c607132",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        that.setData({
          letterOfCommitmentArguments: res.data.data.letterOfCommitmentArguments
        });
      } else {
        wx.showToast({
          title: '获取公证文档参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
    }
  });
};

// 4页4 查询询问笔录参数 getEnquiryRecordArgumentsByTaskIdAndUserInfoId
client.getEnquiryRecordArgumentsByTaskIdAndUserInfoId = function (taskId, that) {
  wx.request({
    url: ip + "233e3cee-befa-40bf-95c0-4178f79ffc32",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        var taskUserNames = "";
        for (var i = 0; i < res.data.data.enquiryRecordArguments.taskUserNames.length; i++) {
          taskUserNames += res.data.data.enquiryRecordArguments.taskUserNames[i] + "、"
        }
        var contractNames = "";
        for (var i = 0; i < res.data.data.enquiryRecordArguments.contractNames.length; i++) {
          contractNames += "《" + res.data.data.enquiryRecordArguments.contractNames[i] + "》、"
        }
        that.setData({
          enquiryRecordArguments: res.data.data.enquiryRecordArguments,
          taskUserNames: taskUserNames,
          contractNames: contractNames
        });
      } else {
        wx.showToast({
          title: '获取公证文档参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
    }
  });
};

// 电子签名签署合同请求接口
client.electronicSignatureToContract = function (callback, that) {
  wx.showLoading({
    title: '合同签署进行中',
  });
  that.setData({
    canSubmit: false
  });
  wx.request({
    url: ip + "487b721c-4d04-4a8d-a9d5-6ce18df3301f",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.showToast({
          title: '电子签名签署合同成功',
          icon: 'none',
          duration: 1000
        });
        if (wx.getStorageSync('enquireMethod') == "书面询问") {
          // 进入书面询问页面
          wx.redirectTo({
            url: "../../pages/paperAsk/paperAsk?taskId=" + taskId
          });
        } else {
          wx.redirectTo({
            url: "../../pages/online/online?taskId=" + taskId
          });
        }
      } else {
        wx.showToast({
          title: '电子签名签署合同失败',
          icon: 'none',
          duration: 1000
        });
        that.setData({
          canSubmit: true
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
      that.setData({
        canSubmit: false
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 获取用户id接口
client.getUserId = function (callback, taskId1, filePath, that) {
  taskId = taskId1;
  wx.request({
    url: ip + "7cd6e5bb-d6ce-4e8d-b0f2-19ef88c15c68",
    method: "GET",
    data: {
      "page": "0"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      // console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        client.getFileInfo(function (res) {}, res.data.data.serverResponse.content, filePath, that);
      } else {
        wx.showToast({
          title: '获取用户id失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 书面询问获取文件参数接口
client.getFileInfo = function (callback, userId, filePath, that) {
  wx.request({
    url: ip + "e400c168-fa28-4ec8-b48f-d277da6edb4a",
    method: "GET",
    data: {
      "page": "0"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      // console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        var url = "https://gcf.turingsingularity.com/fqfileupload/Primevalfileupload?proname=" + res.data.data.proname +
          "&fileuser=" + res.data.data.fileuser + "&filepassword=" + res.data.data.filepassword +
          // taskID_userid_意愿录制.后缀名）
          "&PrimevalName=" + taskId + "_" + userId + "_意愿录制.mp4";
        console.log("url: " + url);
        that.setData({
          isProgress: true
        });
        client.uploadFile(url, filePath, that);
      } else {
        wx.showToast({
          title: '获取文件参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      callback(res);
    }
  });
};

// 书面询问上传视频文件接口
client.uploadFile = function (url, filePath, that) {
  console.log("filePath: " + filePath);
  const uploadTask = wx.uploadFile({
    url: url,
    filePath: filePath,
    name: 'file',
    header: {
      "Content-Type": "multipart/form-data"
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log("uploadFile: " + JSON.stringify(res));
      console.log(res.statusCode);
      if (res.statusCode == 200) {
        wx.showToast({
          title: '书面询问完成',
          icon: 'none',
          duration: 1000
        });
        var jsonObj = JSON.parse(res.data);
        console.log("jsonObj.data.data.url: " + jsonObj.data.data.url);
        client.willingRecord(jsonObj.data.data.url);
      } else {
        wx.showToast({
          title: '书面询问上传视频失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    }
  });
  uploadTask.onProgressUpdate((res) => {
    that.setData({
      uploadPercent: res.progress,
      uploadText: "上传中（" + res.progress + "%）"
    });
    console.log('上传进度', res.progress);
    console.log('已经上传的数据长度', res.totalBytesSent);
    console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
  });
};

// 书面询问上传后更新参数接口
client.willingRecord = function (filePath) {
  wx.request({
    url: ip + "69f5e92c-5715-4342-bcec-e89f88735e40",
    method: "POST",
    data: {
      taskId: taskId,
      filePath: filePath
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        wx.reLaunch({
          url: "../main/main"
        });
      } else {
        wx.showToast({
          title: '更新参数失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
    }
  });
};

// 视频询问获取UserSig参数接口
client.getUserSig = function (taskId, that) {
  wx.request({
    url: ip + "5d810e91-f83b-48ee-ae5a-035fb4d54cd6",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        that.data.rtcConfig = {
          userID: res.data.data.userId,
          sdkAppID: '1400380514',
          userSig: res.data.data.userSig,
          template: 'grid',
          debugMode: false, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
          beautyLevel: 9, // 默认开启美颜
          enableCamera: true,
          enableMic: true,
          enableAgc: true,
          enableAns: true,
        };
        that.setData({
          rtcConfig: that.data.rtcConfig,
          roomID: res.data.data.latestMeetingId
        });
        that.enterRoom();
      } else {
        wx.showToast({
          title: '获取UserSig失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {}
  });
};

// 视频询问saveContractLiableUserEnquiryVideoAddress接口
client.saveContractLiableUserEnquiryVideoAddress = function (that) {
  wx.request({
    url: ip + "2b4105b6-972a-4a52-9215-7811b1eced93",
    method: "POST",
    data: {
      taskId: taskId
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {} else {
        wx.showToast({
          title: '记录会议失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {}
  });
};

// 视频询问getEnquiryContentFileByTaskIdAndUserInfoId接口
client.getEnquiryContentFileByTaskIdAndUserInfoId = function (taskId1, that) {
  wx.request({
    url: ip + "78204c6a-d4e9-4b1b-a71b-047a0fc33a33",
    method: "POST",
    data: {
      taskId: taskId1
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        that.setData({
          videoSrc: res.data.data.videoSrc
        });
      } else {
        wx.showToast({
          title: '获取在线询问视频记录失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {}
  });
};

// 我的页面获取用户信息请求接口
client.listUsersByUserInfoUserId = function (callback, that) {
  wx.request({
    url: ip + "464d1f55-37fd-4c5f-af62-de359f2f7d28",
    method: "POST",
    data: {
      "page": "0",
      "size": "999999"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      // console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        that.setData({
          userInfo: res.data.data.content
        });
        console.log(JSON.stringify(that.data.userInfo));
      } else {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 我的页面获取合同责任人的违约信息接收手段接口
client.getBreakContractReceivingMeans = function (callback, that) {
  wx.request({
    url: ip + "1b775533-cbcc-4576-b1b6-4a8356916983",
    method: "POST",
    data: {
      taskId: taskId,
      "page": "0",
      "size": "999999"
    },
    header: {
      'context-type': 'application/json',
      'Access-Token': token
    },
    // 调用成功的回调函数
    success: function (res) {
      console.log(taskId);
      console.log(JSON.stringify(res));
      if (res.data.succeed == 0) {
        that.setData({
          breakContractEmail: res.data.data.breakContractEmail,
          breakContractPhone: res.data.data.breakContractPhone,
        });
      } else {
        wx.showToast({
          title: '获取违约信息联系方式失败',
          icon: 'none',
          duration: 1000
        });
      }
    },
    // 调用失败的回调函数
    fail: function (res) {
      wx.showToast({
        title: "网络错误：" + res.errMsg,
        icon: 'none',
        duration: 2000
      });
    },
    // 调用结束的回调函数（调用成功、失败都会执行）
    complete: function (res) {
      wx.hideLoading();
      callback(res);
    }
  });
};

// 获取当前日期
client.getToday = function () {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();
  if (month < 10) {
    month = '0' + month;
  };
  if (day < 10) {
    day = '0' + day;
  };
  // 如果需要时分秒
  // var h = now.getHours();
  // var m = now.getMinutes();
  // var s = now.getSeconds();
  var formatDate = year + '年' + month + '月' + day + '日';
  return formatDate;
}

// 时间戳改为日期显示
client.transTime = function (unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = dateTime.getMonth() + 1;
  var day = dateTime.getDate();
  var timeSpanStr = year + ' 年 ' + month + ' 月 ' + day + ' 日';
  return timeSpanStr;
}

// 倒计时插件
client.countDown = function (that) {
  var seconds = 30;
  var noteId = that.data.lastNoteId + 1;
  that.setData({
    noteYesText: "剩余" + seconds + "s",
    isCanGetCode: false,
    isCanNote: false
  });
  let promise = new Promise((resolve, reject) => {
    let setTimer = setInterval(() => {
      seconds -= 1;
      that.setData({
        noteYesText: "剩余" + seconds + "s"
      });
      console.info(
        that.data.lastNoteId + " 进入 " + noteId + " 倒计时 " + seconds
      );
      // 如果关闭对话框，则当前的和之前的所有倒计时全部结束
      if (that.data.lastNoteId >= noteId) {
        resolve(setTimer);
      }
      if (seconds <= 0) {
        that.setData({
          noteYesText: "获取验证码",
          isCanGetCode: true,
          isCanNote: true,
          buttonBackground: "rgba(38,128,235,1)"
        });
        resolve(setTimer);
      }
    }, 1000);
  });
  promise.then(setTimer => {
    console.info("clearInterval");
    clearInterval(setTimer);
  });
};

module.exports = {
  client: client
};